<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">组 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">组名称</label>
            <input class="mdui-textfield-input" type="text" id='where_name' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">组描述</label>
            <input class="mdui-textfield-input" type="text" id='where_desc' />
        </div>

    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="id,0">组 ID ↑</option>
        <option value="id,1" selected>组 ID ↓</option>
        <option value="name,0">组名称 ↑</option>
        <option value="name,1">组名称 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }
</style>
<script>
    !function () {
        var $ = mdui.$;
        var tb = new table.T($("#table"));

        tb.addField("#");
        tb.addField("组名称");
        tb.addField("描述");
        tb.addField("成员数");
        
        tb.addField("操作");

        var loading = false; // 加载中

        var page = 1; // 当前页
        var size = 1; // 总页数

        var sort_field = 'id'; // 进行排序的字段
        var sort_type = '1'; // 排序方式：0升序1降序

        var where_id = ''; // 筛选数据：组id
        var where_name = ''; // 筛选数据：组名称
        var where_desc = ''; // 筛选数据：组描述


        $('#update').on('click', update);
        $('#sort-select').on('change', () => {
            var v = $('#sort-select').val();
            sort_field = v.split(',')[0];
            sort_type = v.split(',')[1];
            page = 1;
            update();
        });
        $('#where_id').on('change', () => {
            where_id = $('#where_id').val();
            page = 1;
            update();
        });
        $('#where_name').on('change', () => {
            where_name = $('#where_name').val();
            page = 1;
            update();
        })
        $('#where_desc').on('change', () => {
            where_desc = $('#where_desc').val();
            page = 1;
            update();
        })


        tb.on('cellClick', function ({ row, line }) {
                if (line == 4) return;
                groupDetailed(tb.getCell(row, 0));
            });

        function isFilter() {
            return where_id || where_name || where_desc || where_create_time;
        }

        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme')

            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({ error: function(xhr) { dialog.close(); window.parent.mdui.snackbar('加载失败: ' + (xhr.responseJSON?.msg || '网络错误')); },
                url: "/admin/api/get_group_list?p=" + page +
                    '&sort_field=' + encodeURIComponent(sort_field) +
                    '&sort_type=' + encodeURIComponent(sort_type) +
                    '&where_id=' + encodeURIComponent(where_id) +
                    '&where_name=' + encodeURIComponent(where_name) +
                    '&where_desc=' + encodeURIComponent(where_desc) ,

                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        tb.endLoading();
                        loading = false;

                        size = res.data.size;

                        if (size) {
                            $('.pages').show();
                            var data = res.data.data
                            for (let d of data) {
                                let name_ = $(`<div class="mdui-chip">
  <img class="mdui-chip-icon" src="avatar1.jpg"/>
  <span class="mdui-chip-title">Example Chip</span>
</div>`);
                                name_.find('img').attr('src', d.img);
                                name_.find('span').text(d.name);

                                let membersBtn = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '查看成员'}"><i class="mdui-icon material-icons">group</i></button>`)
                                let editBtn = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '编辑组'}"><i class="mdui-icon material-icons">create</i></button>`)
                                let deleteBtn = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '删除组'}"><i class="mdui-icon material-icons">delete</i></button>`)

                                membersBtn.on('click', () => viewMembers(d.id)); editBtn.on('click', () => editGroup(d.id)); deleteBtn.on('click', () => deleteGroup(d.id));

                                tb.addRow([
                                    d.id, {
                                        type: "el",
                                        el: name_
                                    },
                                    d.description,
                                    d.member_count,
                                    {
                                        type: 'el',
                                        el: $('<div></div>').append(membersBtn).append(editBtn).append(deleteBtn)
                                    }
                                ]);
                            }
                        } else {
                            $('.pages').hide();
                        }
                        renderPages();
                    }
                    else {
                        window.parent.mdui.snackbar(res.msg || "加载失败")
                    }
                }
            });
        }

        function renderPages() {
            $(".pages").html('');
            var omit = true; // 是否省略

            // 添加向左翻页按钮
            var left = $(`<button class="mdui-btn left">&lt;</button>`)
            left.appendTo($(".pages"));

            for (let i = 0; i < size; i++) {
                let toadd = false; // 是否要添加页数按钮

                if (i === 0) toadd = true; // 第一页要添加
                if (i === size - 1) toadd = true; // 最后一页要添加
                if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
                if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
                if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

                if (toadd) {
                    // 渲染页数按钮
                    let button = $(`<button class="mdui-btn ${(i + 1) == page ? `mdui-btn-active` : ""} page-num">${i + 1}</button>`);
                    button.on("click", () => { // 点击事件
                        page = Number(i + 1);
                        update();
                    })
                    button.appendTo($(".pages"));
                    omit = true;
                } else {
                    if (omit) {
                        $(`<button class="mdui-btn" disabled>...</button>`).appendTo($(".pages"));
                        omit = false;
                    }
                }
            }

            // 添加向右翻页按钮
            var right = $(`<button class="mdui-btn right">&gt;</button>`)
            right.appendTo($(".pages"));

            // 根据条件禁用按钮
            left.prop("disabled", page === 1);
            right.prop("disabled", page === size)

            // 添加点击事件
            left.on("click", () => { // 向左
                page -= 1
                update();
            })

            right.on("click", () => { // 向右
                page += 1
                update();
            })
        }

        function groupDetailed(id) {
            const dialog = $.dialog({
                closeOnEsc: true,
                closeOnOutsideClick: true,
                history: false,
                cssClass: "ds-user-detailed ds-loadable",
                content: `
<div class="mdui-list-item mdui-p-l-0">
    <div class="mdui-list-item-avatar">
        <img src="" id='ds-ud-img'>
    </div>
    <div class="mdui-list-item-content" id='ds-ud-name'></div>
</div>

<p class='mdui-typo-subheading'>组基本信息</p><table class='mdui-table mdui-shadow-0' id='ds-ud-basic'></table>

<p class='mdui-typo-subheading'>组成员信息</p><div class='ds-ud-members'></div>
<p class='mdui-typo-subheading'>组权限信息</p><div class='ds-ud-permissions'></div>
<table class="mdui-table mdui-shadow-0" id='ds-ud-register'></table>

<p class='mdui-typo-subheading'>创建与更新</p><table class='mdui-table mdui-shadow-0' id='ds-ud-time'></table>

<div class="mdui-spinner"></div>
`
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "/admin/api/get_group_data?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;

                    content.find('.mdui-spinner').remove();

                    // 用户头像和昵称
                    content.find('#ds-ud-img').attr('src', data.img);
                    content.find('#ds-ud-name').text(data.name);

                    // 信息表
                    const tableData = { 
                        '#ds-ud-basic': [
                            ['组 ID', data.id], 
                            ['组名称', data.title], 
                            ['成员数量', data.member_count] 
                        ],
                    };
                    const permissions = content.find('.ds-ud-permissions'); 
                    permissions.html('<div class="mdui-list"></div>'); 
                    (data.permissions || []).forEach(perm => {permissions.find('.mdui-list').append(`<div class="mdui-list-item mdui-ripple"><i class="mdui-list-item-icon mdui-icon material-icons">check_circle</i><div class="mdui-list-item-content">${perm.name}</div></div>`); });

                    for (let k in tableData) {
                        let table = content.find(k);

                        for (let i = 0; i < tableData[k].length; i++) {
                            let tr = $(`<tr></tr>`);

                            for (let j = 0; j < tableData[k][i].length; j++) {
                                let td = $(`<td></td>`);

                                td.text(tableData[k][i][j]);
                                tr.append(td);
                            }

                            table.append(tr);
                        }
                    }


                    dialog.handleUpdate();
                }
            });
        }
        function editGroup(id) { 
            var saving = false; 
            const dialog = $.dialog({ 
                title: '修改组', 
                history: false, 
                cssClass: 'ds-loadable', 
                content: `<div class='mdui-textfield'><label class='mdui-textfield-label'>组名称</label><input class='mdui-textfield-input' type='text' id='ds-change-name' required /></div><div class='mdui-textfield'><label class='mdui-textfield-label'>组描述</label><textarea class='mdui-textfield-input' id='ds-change-desc'></textarea></div><div class='mdui-spinner'></div>`, 
                buttons: [
                    { 
                        text: '取消', 
                        close: false, 
                        onClick() { 
                            if (content.find('.mdui-spinner').length || saving) return false; 
                            dialog.close(); 
                        } 
                    }, { 
                        text: '保存', 
                        close: false, 
                        onClick: function () { 
                            if (content.find('.mdui-spinner').length || saving) return false; 
                            const name = content.find('#ds-change-name').val(); 
                            const description = content.find('#ds-change-desc').val(); 

                            if (!name) { 
                                return mdui.snackbar('请填写组名称'); 
                            } 

                            content.find('input,textarea,a,select').attr('disabled', ''); 
                            saving = true; 

                            saveGroupApi(id, { name, description }) 
                                .then(() => { 
                                    dialog.close(); 
                                    update(); 
                                    saving = false; 
                                    return mdui.snackbar("保存成功") 
                                }, (msg) => { 
                                    saving = false; 
                                    content.find('input,textarea,a,select').removeAttr('disabled'); 
                                    return mdui.snackbar(msg || "保存失败") 
                                }); 
                        } 
                    } 
                ] 
            }); 

            const content = dialog.$element 
            window.parent.mdui.mutation(); 

            $.ajax({ 
                url: '/admin/api/get_group_data?id='+id, 
                dataType: 'json', 
                success: function (res) { 
                    if (res.code != 200) { 
                        dialog.close(); 
                        return mdui.snackbar(res.msg || "加载失败") 
                    } 

                    const data = res.data; 
                    content.find('#ds-change-name').val(data.name); 
                    content.find('#ds-change-desc').val(data.description); 

                    window.parent.mdui.updateTextFields(); 
                    window.parent.mdui.mutation(); 

                    content.find('.mdui-spinner').remove(); 
                    dialog.handleUpdate(); 
                } 
            }); 
        } 

        function saveGroupApi(id, formData) { 
            return new Promise((resolve, reject) => { 
                $.ajax({ error: function(xhr) { dialog.close(); window.parent.mdui.snackbar('加载失败: ' + (xhr.responseJSON?.msg || '网络错误')); }, 
                    url: '/admin/api/save_group', 
                    method: 'POST', 
                    data: { id, ...formData }, 
                    dataType: 'json', 
                    success: function (res) { 
                        if (res.code == 200) { 
                            resolve() 
                        } else { 
                            reject(res.msg) 
                        } 
                    }, 
                    error: function (res) { 
                        reject(res.responseJSON?.msg || "网络错误") 
                    } 
                }); 
            }) 
        } 
        function viewMembers(id) {
            const dialog = $.dialog({
                closeOnEsc: true,
                closeOnOutsideClick: true, 
                title: '组成员', 
                content: `<div class='mdui-spinner'></div>`, 
                onOpen: () => { 
                    $.ajax({ error: function(xhr) { dialog.close(); window.parent.mdui.snackbar('加载失败: ' + (xhr.responseJSON?.msg || '网络错误')); }, 
                        url: '/admin/api/get_group_members?id='+id, 
                        success: (res) => { 
                            const membersContainer = dialog.$element.find('.ds-ud-members');
                            membersContainer.html(''); 
                            res.data.forEach(member => { 
                                const memberEl = $(`<div class='mdui-chip'><span class='mdui-chip-title'>${member.name} (ID: ${member.id})</span></div>`); 
                                membersContainer.append(memberEl); 
                            }); 
                            dialog.handleUpdate(); 
                        } 
                    }); 
                } 
            }); 
        } 
        function deleteGroup(id) { 
            mdui.$.confirm('确定要删除这个组吗？', '确认删除', function () { 
                $.ajax({ 
                    url: '/admin/api/delete_group', 
                    method: 'POST', 
                    data: { id: id }, 
                    dataType: 'json', 
                    success: function (res) { 
                        if (res.code === 200) { 
                            mdui.snackbar("删除成功") 
                            update(); 
                        } else { 
                            mdui.snackbar(res.msg || "删除失败"); 
                        } 
                    }, 
                    error: function () { 
                        mdui.snackbar("网络错误"); 
                    } 
                }); 
            }); 
        }

    }();
</script>